import React, { useState, useEffect } from 'react';
import { List, Button, Skeleton, Avatar, message } from 'antd';
import style from './usersRecommend.module.css'
import { post } from './../../utils/post';
import { withRouter } from "react-router-dom";
const _id= JSON.parse(localStorage.getItem('usersMessage'))._id
const UsersRecommend = (props) => {
    const [skip, setSkip] = useState(0);
    const [state, setState] = useState({
        initLoading: true,
        loading: false,
        data: [],
        list: []
    });
    const [UnFocus, changeUnFocus] = useState([]);//未关注的
    const [focus, changeFocus] = useState([]);//已关注的
    useEffect(() => {
        // 发送一个请求
        post('/api/getAllusers', { skip }).then(res => {
            setState(
                {
                    ...state,
                    initLoading: false,
                    loading: false,
                    data: res.data.data,
                    list: res.data.data
                }
            )
        })

    }, []);
    useEffect(() => {
        post('/api/searchAttention', { _id}).then(res => {//获取已关注
            let Focused = res.data.data.allAttention;
            // console.log(Focused,"focused");
            if (Focused !== null&&Focused!==undefined) {
                let map = getDifferenceSetB(Focused, state.list, '_id')
                if (map.length < 1) {
                    message.success('前三个你已经关注了')
                }
                changeUnFocus(map);
                changeFocus(Focused);
            } else {
                console.log(state.list,'state.list....');
                changeFocus([]);
                changeUnFocus(state.list);
            }

        })
    }, [state.list])

    const getDifferenceSetB = (arr1, arr2, typeName) => {//求差集函数，别动
        return Object.values(arr1.concat(arr2).reduce((acc, cur) => {
            if (acc[cur[typeName]] && acc[cur[typeName]][typeName] === cur[typeName]) {
                delete acc[cur[typeName]];
            } else {
                acc[cur[typeName]] = cur;
            }
            return acc;
        }, {}));
    }
    const seeMore = (e) => {
        message.info(`${e.nickname} -- ${e.profile}`);
        let newFocus = {
            profile: e.profile, nickname: e.nickname, _id: e._id
        }
        let arr = [...focus, newFocus];
        // console.log(focus,"focus");
        // console.log(UnFocus,"UnFocus");
        // console.log(arr,"arr")
        post('/api/addAttention', { _id, others: arr }).then(res => {
            if (res.data.meta.status === 200) {//成功
                let arr1 = [newFocus];
                let newUnFocus = getDifferenceSetB(arr1, UnFocus, '_id')
                // console.log(res.data.data.userInfo)
                // newUnFocus.push(res.data.data.userInfo)
                // console.log(newUnFocus);
                changeUnFocus(newUnFocus);
                changeFocus(arr)
            }
        })
    }
    const count = 3

    const onLoadMore = () => {
        setSkip(skip + 3);
        console.log(skip, 'skip');
        setState(
            {
                ...state,
                loading: true,
                list: state.data.concat(
                    [...new Array(count)].map(() => ({ nickname: '', avater: '', profile: '', _id: '' })),
                ),
            }
        )
        // 再去发送请求
        //  然后去更新,更新成功则重新让loading为false
        // const data = state.data.concat(resuluts.data);
        post('/api/getAllusers', { skip: skip + 3 }).then(res => {
            console.log(res, '----getAllusers');
            if (res.data.data.length < 1) {
                setState({ ...state, loading: false })
                message.error('没有更多数据了')
            }
            console.log(state.data, 'state.data');
            setState(
                {
                    ...state,
                    loading: false,
                    data: state.data.concat(res.data.data),
                    list: state.data.concat(res.data.data)
                }
            )
        })
    }
    const loadMore = !state.initLoading && !state.loading ? (
        <div
            style={{
                textAlign: 'center',
                marginTop: 12,
                height: 32,
                lineHeight: '32px',
            }}
        >
            <Button className={`${style.moreButton}`} onClick={onLoadMore}>loading more</Button>
        </div>
    ) : null;

    return (
        <div className={`${style.body}`}>
            <List
                header={<strong>
                    Popular Bloggers</strong>}
                className={`${style.list}`}
                size="large"
                bordered
                loading={state.initLoading}
                loadMore={loadMore}
                dataSource={UnFocus}
                renderItem={
                    item => <List.Item>
                        <div className={`${style.listItem}`}>
                            <Skeleton title={false} loading={item.loading} active>
                                <List.Item.Meta
                                    avatar={<Avatar onClick={() => { props.history.push(`/index/${item._id}`) }} src={item.avater} />}
                                    title={<p onClick={() => { props.history.push(`/index/${item._id}`) }}>{item.nickname}</p>}
                                    description={item.profile}
                                />
                            </Skeleton>
                            <Button type="primary" className={`${style.button}`} onClick={() => {
                                seeMore(item)
                            }} >follow</Button>
                        </div>

                    </List.Item>
                }
            />
        </div>
    )
}
export default withRouter(UsersRecommend);